#! /usr/bin/python27
# -*- coding: UTF-8 -*-
from django.http.response import HttpResponse
from django.http import HttpResponseRedirect
from .models import User
from django.shortcuts import render_to_response, redirect
from form import LoginForm
from django.contrib.auth import authenticate, login as auth_login,logout as auto_logout


# 登录
def login(request):
    error = []
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            # 获取表单用户密码
            data = form.cleaned_data
            username = data['username']
            password = data['password']
            if login_validate(request, username, password):
                return redirect('index', {'username': username})
            else:
                error.append(u'请重新输入密码')
        else:
            error.append(u'请重新输入用户名和密码')
    else:
        form = LoginForm()
    return render_to_response('login.html', {'error': error, 'form': form})


def login_validate(request, username, password):
    _rtValue = False
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            auth_login(request, user)
            return True
    return _rtValue


def index(request):
    return render_to_response('index.html')


def create_project(request):
    return HttpResponse("CreateProject HEML!")


def create_user(request):
    return HttpResponse("CreateUser HEML!")
